package huawei;

import java.util.Arrays;

/**
 * @author: yfq
 * @date: 2023/3/13 10:42
 * @description:
 */
public class MergerSort {
    public static void main(String[] args) {
//        int[] arr = {2, 5, 4, 3, 2, 1};
        int[] arr = {10, 5, 4, 3, 2, 1, 5, 1, 8, 9, 3, 6};
        partition(arr, 0, arr.length - 1, new int[arr.length]);

        System.out.println(Arrays.toString(arr));
    }

    public static void partition(int[] arr, int start, int end, int[] temp) {
        if (start < end) {
            int mid = (start + end) >> 1;

            partition(arr, start, mid, temp);

            partition(arr, mid + 1, end, temp);

            merger(arr, start, mid, end, temp);
        }
    }

    public static void merger(int[] arr, int start, int mid, int end, int[] temp) {
        int i = start;
        int k = mid + 1;
        int index = start;

        while (i <= mid && k <= end) {
            if (arr[i] <= arr[k]) {
                temp[index] = arr[i];
                i++;
                index++;
            } else {
                temp[index] = arr[k];
                k++;
                index++;
            }
        }

        while (i <= mid) {
            temp[index] = arr[i];
            i++;
            index++;
        }

        while (k <= end) {
            temp[index] = arr[k];
            k++;
            index++;
        }

        for (int j = start; j <= end; j++) {
            arr[j] = temp[j];
        }

    }
}
